import re
import psutil
import requests
import platform

from src.utils.motdpe import BedrockServer

OS_PLATFORM = platform.system()
MB_TO_B = 1024 ** 2
GB_TO_B = MB_TO_B * 1024


class Tool:
    # 基岩版motd api
    @staticmethod
    def motd_pe(host: str) -> str:
        address = host
        if not host:
            return "未指定服务器地址！"
        try:
            mc_status = BedrockServer.lookup(host)
            msg = f"[MCBE服务器信息]\n状态: online\n地址: {address}\nmotd: {mc_status.motd}\n" \
                  f"协议版本: {mc_status.protocol}\n游戏版本: {mc_status.version}\n" \
                  f"在线人数: {mc_status.players_online}/{mc_status.players_max}\n存档名称: {mc_status.map}\n" \
                  f"游戏模式: {mc_status.gamemode}\n延迟: {round(mc_status.latency, 2)}ms"
            return msg
        except Exception as err:
            return f"[MCBE服务器信息]\n操作失败：{err}"

    # 云黑查询 api
    @classmethod
    def black_be(cls, player: str) -> str:
        url = f"https://api.blackbe.work/openapi/v3/check/?name={player}"
        # 若为qq号则切换url
        re_player = re.match("\\d+", player)
        if re_player and re_player.group() == player:
            url = f"https://api.blackbe.work/openapi/v3/check/?qq={player}"
        try:
            back = requests.get(url, timeout=5).json()
            if back["status"] != 2000:
                return back['message'] + "~"
            else:
                back['message'] = "存在违规行为"
            # 调用api根据玩家名查询xuid
            uid_player = cls.xuid_search(back['data']['info'][0]['name'])
            if uid_player == "查询失败~":  # pragma: no cover
                uid_player = back['data']['info'][0]['xuid']
            # 生成云黑信息并返回
            msg = f"[MCBE云黑信息]\n" \
                  f"玩家id: {back['data']['info'][0]['name']}\n" \
                  f"记录qq: {back['data']['info'][0]['qq']}\n" \
                  f"玩家xuid: {uid_player}\n" \
                  f"记录状态: {back['message']}\n" \
                  f"记录级别: {back['data']['info'][0]['level']}\n" \
                  f"条目uuid: {back['data']['info'][0]['uuid']}\n" \
                  f"记录原因: {back['data']['info'][0]['info']}"
            return msg
        except Exception:  # pragma: no cover
            return "响应超时~"

    # xuid查询 api
    @staticmethod
    def xuid_search(name: str) -> str:
        try:
            uid_data = requests.get(
                f"https://api.blackbe.work/openapi/v3/utils/xuid?gamertag={name}",
                timeout=10).json()
            return uid_data['data']['xuid']
        except Exception:
            return f"查询失败~"

    # 获取服务器状态
    @staticmethod
    def get_status(raw=False, text=""):
        mem = psutil.virtual_memory()
        disks = psutil.disk_partitions(True)
        # 存在bug: 将导致编译后程序调用时重启
        # cpu_name = cpuinfo.get_cpu_info()["brand_raw"]
        cpu_rate = psutil.cpu_percent(1)
        cpu_freq = round(psutil.cpu_freq().current / 1000, 1)
        cpu_count = psutil.cpu_count(logical=False)
        mem_used = int(mem.used / MB_TO_B)
        mem_total = int(mem.total / MB_TO_B)
        mem_rate = round(mem_used / mem_total * 100, 2)
        # 磁盘使用状况
        disks_info = []
        if OS_PLATFORM == 'Windows':  # pragma: no cover
            for disk in disks:
                try:
                    disk_info = psutil.disk_usage(disk.device)
                    disk_head = disk.device.replace("\\", "")
                except Exception:
                    continue
                disks_info.append({
                    "symbol": disk_head,
                    "disk_used": int(disk_info.used / GB_TO_B),
                    "disk_total": int(disk_info.total / GB_TO_B)
                })
        else:  # pragma: no cover
            disk_info = psutil.disk_usage('/')
            disks_info.append({
                "symbol": "/",
                "disk_used": int(disk_info.used / GB_TO_B),
                "disk_total": int(disk_info.total / GB_TO_B)
            })
        if raw:
            return {
                "cpu_count": cpu_count,
                "cpu_freq": cpu_freq,
                "cpu_rate": cpu_rate,
                "mem_rate": mem_rate,
                "mem_used": mem_used,
                "mem_total": mem_total,
                "disks_info": disks_info
            }
        else:
            disks_info_text = ""
            for d_info in disks_info:
                disks_info_text += f"\n{d_info['symbol']} {d_info['disk_used']}GB/{d_info['disk_total']}GB"
            # 含占位符的文本处理
            if not text:
                text = "CPU信息: %cpu_count核 %cpu_freqGHz\n" \
                       "CPU使用: %cpu_rate%\n" \
                       "内存使用: %mem_rate%\n" \
                       "%mem_usedMB/%mem_totalMB\n" \
                       "磁盘使用: %disks_info"
            text = (text.replace("%cpu_count", str(cpu_count))
                    .replace("%cpu_freq", str(cpu_freq))
                    .replace("%cpu_rate", str(cpu_rate))
                    .replace("%mem_rate", str(mem_rate))
                    .replace("%mem_used", str(mem_used))
                    .replace("%mem_total", str(mem_total))
                    .replace("%disks_info", disks_info_text))
            return text